package com.aizhixin.lab.project.course.service;

import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import com.aizhixin.lab.common.core.DataValidity;
import com.aizhixin.lab.common.utils.ExcelUtil;
import com.aizhixin.lab.common.utils.PageJdbcUtil;
import com.aizhixin.lab.company.repository.UserRepository;
import com.aizhixin.lab.project.course.data.GroupMemberData;
import com.aizhixin.lab.project.course.data.GroupResultData;
import com.aizhixin.lab.project.course.domain.*;
import com.aizhixin.lab.project.course.entity.ProjectClassStu;
import com.aizhixin.lab.project.course.entity.ProjectGroup;
import com.aizhixin.lab.project.course.entity.ProjectPeopleEvaluating;
import com.aizhixin.lab.project.course.entity.ProjectReply;
import com.aizhixin.lab.project.course.repository.*;
import com.aizhixin.lab.project.course.vo.ProjectMinutesVo;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.math.BigDecimal;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.*;

@Slf4j
@Service
@Transactional
public class ProjectPeopleEvaluatingService {
    @Autowired
    private ProjectPeopleEvaluatingRepository projectPeopleEvaluatingRepository;
    @Autowired
    private ProjectGroupRepository projectGroupRepository;
    @Autowired
    private ProjectClassStuRepository stuRepository;
    @Autowired
    private PageJdbcUtil pageJdbcUtil;
    @Autowired
    private UserRepository userRepository;
    @Autowired
    private ProjectReplyRepository replyRepository;


    public void importEvaluating(MultipartFile file,String releaseProjectReplyId,String projectId,Long createBy) throws IOException {
        boolean excel2003 = ExcelUtil.isExcel2003(file.getName());
        ExcelUtil excelUtil;
        if (!excel2003){
             excelUtil = new ExcelUtil(file.getInputStream(), "2003");
        }else {
             excelUtil = new ExcelUtil(file.getInputStream(), "2000");
        }
        Sheet sheetAt = excelUtil.getWorkbook().getSheetAt(0);
        int lastRowNum = sheetAt.getLastRowNum();
        List<ProjectPeopleEvaluating> projectPeopleEvaluatingList = new ArrayList<>();
        for (int i = 1; i < lastRowNum; i++) {
            Row row = sheetAt.getRow(i);
            if (Objects.isNull(excelUtil.getCellValueToString(row.getCell(0)))){
                continue;
            }
            ProjectPeopleEvaluating projectPeopleEvaluating = new ProjectPeopleEvaluating();
            projectPeopleEvaluating.setId(UUID.randomUUID().toString());
            projectPeopleEvaluating.setReleaseProjectReplyId(releaseProjectReplyId);
            projectPeopleEvaluating.setProjectId(projectId);
            projectPeopleEvaluating.setCreatedBy(createBy);
            projectPeopleEvaluating.setDeleteFlag(DataValidity.VALID.getState());
            projectPeopleEvaluating.setText(excelUtil.getCellValueToString(row.getCell(1)));
            projectPeopleEvaluating.setWeight(Double.parseDouble(excelUtil.getCellValueToString(row.getCell(2))));
            projectPeopleEvaluating.setDescription(excelUtil.getCellValueToString(row.getCell(3)));
            projectPeopleEvaluating.setType(Integer.parseInt(excelUtil.getCellValueToString(row.getCell(4))));
            projectPeopleEvaluating.setCreatedDate(new Date());
            projectPeopleEvaluating.setCode(new Date().getTime()+"");
            projectPeopleEvaluatingList.add(projectPeopleEvaluating);
        }
        projectPeopleEvaluatingRepository.save(projectPeopleEvaluatingList);
    }
    public HSSFWorkbook exportEvaluating(String projectId){
        HSSFWorkbook wb = new HSSFWorkbook();
        HSSFSheet sheet = wb.createSheet("evaluating");
        HSSFRow row = sheet.createRow(0);
        row.createCell(0).setCellValue("序号");
        row.createCell(1).setCellValue("考核维度名称");
        row.createCell(2).setCellValue("权重");
        row.createCell(3).setCellValue("描述");
        row.createCell(4).setCellValue("类型(1:小组,2:个人)");
        List<ProjectPeopleEvaluating> evaluatingList = projectPeopleEvaluatingRepository.findByProjectIdAndDeleteFlag(projectId, DataValidity.VALID.getState());
        int i=1;
        for (ProjectPeopleEvaluating projectPeopleEvaluating : evaluatingList) {
            HSSFRow row1 = sheet.createRow(i);
            row1.createCell(0).setCellValue(i);
            row1.createCell(1).setCellValue(projectPeopleEvaluating.getText());
            row1.createCell(2).setCellValue(projectPeopleEvaluating.getWeight());
            row1.createCell(3).setCellValue(projectPeopleEvaluating.getDescription());
            row1.createCell(4).setCellValue(projectPeopleEvaluating.getType());
            i++;
        }
        return wb;
    }
    public List<GroupResultData> findEvaluationResult(String releaseProjectReplyId,String projectId,Long createdBy,Boolean isComplexTable){
        List<GroupResultData> data=new ArrayList<>();
        Map<String,ProjectPeopleEvaluating> weightMap=new HashMap<>();
        Boolean isDefault=false;
        List<ProjectPeopleEvaluating> evaluatingList = projectPeopleEvaluatingRepository.findByReleaseProjectReplyIdAndDeleteFlag(releaseProjectReplyId, DataValidity.VALID.getState());
        if (evaluatingList.size()==0){
            evaluatingList=projectPeopleEvaluatingRepository.findByReleaseProjectReplyIdAndDeleteFlag("0",DataValidity.VALID.getState());
            isDefault=true;
        }
        evaluatingList.forEach(item->{
            weightMap.put(item.getId(),item);
        });
        List<ProjectGroup> projectGroupList = projectGroupRepository.findByProjectIdAndDeleteFlag(projectId, DataValidity.VALID.getState());
        projectGroupList.forEach(item->{
            GroupResultData groupResultData = new GroupResultData();
            groupResultData.setGroupId(item.getId());
            groupResultData.setGroupName(item.getGroupName());
            List<GroupMemberData> dataList=new ArrayList<>();
            List<ProjectReply> projectReplyList1 = replyRepository.findByReleaseProjectReplyIdAndReplyObjectIdAndDeleteFlagAndCreatedBy(releaseProjectReplyId,item.getId(), DataValidity.VALID.getState(),createdBy);
            Integer i = sum(projectReplyList1, weightMap).intValue();
            List<ProjectClassStu> stuList = stuRepository.findByGroupIdAndDeleteFlagAndProjectId(item.getId(), DataValidity.VALID.getState(), projectId);
            stuList.forEach(stu->{
                GroupMemberData groupMemberData = new GroupMemberData();
                groupMemberData.setStuId(stu.getStuId());
                groupMemberData.setRole(stu.getRole());
                groupMemberData.setStuName(userRepository.findByIdAndDeleteFlag(stu.getStuId(),DataValidity.VALID.getState()).getName());
                List<ProjectReply> projectReplyList = replyRepository.findByReleaseProjectReplyIdAndReplyObjectIdAndDeleteFlagAndCreatedBy(releaseProjectReplyId, stu.getStuId().toString(), DataValidity.VALID.getState(),createdBy);
                if (isComplexTable){
                    List<KeyValueDomain> keyValueDomains=new ArrayList<>();
                    projectReplyList.forEach(reply->{
                        KeyValueDomain keyValueDomain = new KeyValueDomain();
                        keyValueDomain.setKey(weightMap.get(reply.getEvaluatingId()).getText());
                        keyValueDomain.setValue(reply.getScore());
                        keyValueDomains.add(keyValueDomain);
                    });
                    groupMemberData.setKeyValueDomains(keyValueDomains);
                }
                groupMemberData.setPersonalEvaluationGrade(sum(projectReplyList,weightMap).intValue());
                groupMemberData.setGroupEvaluationGrade(i);
                groupMemberData.setSynthesizeGrade((groupMemberData.getGroupEvaluationGrade()+groupMemberData.getPersonalEvaluationGrade())/2);
                dataList.add(groupMemberData);
            });
            groupResultData.setGroupMemberDataList(dataList);
            data.add(groupResultData);
        });
        return data;
    }
    private BigDecimal sum(List<ProjectReply> projectReplyList,Map<String,ProjectPeopleEvaluating> weightMap){
        BigDecimal bigDecimal = new BigDecimal("0");
            for (ProjectReply item:projectReplyList) {
            BigDecimal a = new BigDecimal(item.getScore());
            bigDecimal= a.multiply(new BigDecimal(weightMap.get(item.getEvaluatingId()).getWeight())).add(bigDecimal);
        }
        return bigDecimal;
    }

    RowMapper<ProjectEvaluatingaTableDomain> projectEvaluatingaTableDomainRowMapper = new RowMapper<ProjectEvaluatingaTableDomain>() {
        @Override
        public ProjectEvaluatingaTableDomain mapRow(ResultSet rs, int rowNum) throws SQLException {
            ProjectEvaluatingaTableDomain domain = new ProjectEvaluatingaTableDomain();
            domain.setId(rs.getString("id"));
            domain.setText(rs.getString("text"));
            return domain;
        }
    };


    public void save(ProjectPeopleEvaluatingListDomain domain) {
        if (!StringUtils.isEmpty(domain.getReleaseProjectReplyId())) {
            projectPeopleEvaluatingRepository.deleteByReleaseProjectReplyId(domain.getReleaseProjectReplyId());
        }
        if (domain.getType() == null) {
            for (ProjectPeopleEvaluatingDomain data : domain.getProjectPeopleEvaluatingDomainList()) {
                ProjectPeopleEvaluating peopleEvaluating = new ProjectPeopleEvaluating();
                BeanUtils.copyProperties(data, peopleEvaluating);
                if (StringUtils.isEmpty(peopleEvaluating.getId())){
                    peopleEvaluating.setId(UUID.randomUUID().toString());
                    peopleEvaluating.setCreatedDate(new Date());
                }
                peopleEvaluating.setReleaseProjectReplyId(domain.getReleaseProjectReplyId());
                peopleEvaluating.setDeleteFlag(DataValidity.VALID.getState());
                peopleEvaluating.setCode(String.valueOf(System.currentTimeMillis()));
                peopleEvaluating.setType(data.getType());
                peopleEvaluating.setWeight(data.getWeight() / 100);
                projectPeopleEvaluatingRepository.save(peopleEvaluating);
            }
        } else {
            if (domain.getType() == 2) {
                if (domain.getProjectPeopleEvaluatingDomainList().size() > 0) {
                    projectPeopleEvaluatingRepository.deleteByProjectId(domain.getProjectPeopleEvaluatingDomainList().get(0).getProjectId());
                }
                for (ProjectPeopleEvaluatingDomain data : domain.getProjectPeopleEvaluatingDomainList()) {
                    ProjectPeopleEvaluating peopleEvaluating = new ProjectPeopleEvaluating();
                    BeanUtils.copyProperties(data, peopleEvaluating);
                    peopleEvaluating.setId(UUID.randomUUID().toString());
                    peopleEvaluating.setCreatedDate(new Date());
                    peopleEvaluating.setReleaseProjectReplyId(domain.getReleaseProjectReplyId());
                    peopleEvaluating.setDeleteFlag(DataValidity.VALID.getState());
                    peopleEvaluating.setCode(String.valueOf(System.currentTimeMillis()));
                    peopleEvaluating.setType(data.getType());
                    peopleEvaluating.setWeight(data.getWeight() / 100);
                    projectPeopleEvaluatingRepository.save(peopleEvaluating);
                }
            }
            if (domain.getType() == 1) {
                List<ProjectPeopleEvaluating> projectPeopleEvaluatingList = projectPeopleEvaluatingRepository.findByProjectIdAndDeleteFlag("0", 0);
                projectPeopleEvaluatingRepository.deleteByProjectId(domain.getProjectId());
                for (ProjectPeopleEvaluating data : projectPeopleEvaluatingList) {
                    ProjectPeopleEvaluating peopleEvaluating = new ProjectPeopleEvaluating();
                    BeanUtils.copyProperties(data, peopleEvaluating);
                    peopleEvaluating.setReleaseProjectReplyId(domain.getReleaseProjectReplyId());
                    peopleEvaluating.setId(UUID.randomUUID().toString());
                    peopleEvaluating.setCreatedDate(new Date());
                    peopleEvaluating.setCode(String.valueOf(System.currentTimeMillis()));
                    peopleEvaluating.setProjectId(domain.getProjectId());
                    projectPeopleEvaluatingRepository.save(peopleEvaluating);
                }
            }
        }
    }
    public List<ProjectEvaluatingaTableDomain> findEvaluatingTableHade(QueryProjectReplyDomain domain){
        String sql="select code as id, text from t_project_people_evaluating where type = '" + domain.getReplyType() + "' and release_project_reply_id = '" + domain.getReleaseProjectReplyId() + "'" ;
        List<ProjectEvaluatingaTableDomain> projectEvaluatingaTableDomainList = pageJdbcUtil.getInfo(sql, projectEvaluatingaTableDomainRowMapper);
        return projectEvaluatingaTableDomainList;
    }

}
